<template>
    <div class="login-wrap" :class="{ 'night-mode': isNightMode }">
        <div class="bubbles">
            <div class="bubble" v-for="i in 15" :key="i"></div>
        </div>
        <div class="floating-shapes">
            <div class="shape circle"></div>
            <div class="shape square"></div>
            <div class="shape triangle"></div>
        </div>
        <div class="theme-toggle" @click="toggleTheme">
            <el-icon :size="24" :color="isNightMode ? '#fff' : '#000'">
                <component :is="isNightMode ? 'Sunny' : 'Moon'" />
            </el-icon>
        </div>
        <el-form :label-position="labelPosition" label-width="auto" :model="registerForm" class="login-container"
            :rules="rules" ref="ruleFormRef">
            <el-form>
                <div class="center">
                    NERV在线考试系统
                </div>
            </el-form>
            <el-form-item label="" prop="username">
                <el-input v-model="registerForm.username" placeholder="请输入用户名" clearable>
                    <template #prefix>
                        <el-icon class="input-icon">
                            <UserFilled />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="" prop="schoolNumber">
                <el-input v-model="registerForm.schoolNumber" placeholder="请输入学号/工号" clearable>
                    <template #prefix>
                        <el-icon class="input-icon">
                            <UserFilled />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="" prop="password">
                <el-input v-model="registerForm.password" show-password type="password" placeholder="请输入密码" clearable>
                    <template #prefix>
                        <el-icon class="input-icon">
                            <Lock />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="" prop="reType">
                <el-input v-model="registerForm.reType" type="password" placeholder="请再次输入密码" show-password clearable>
                    <template #prefix>
                        <el-icon class="input-icon">
                            <Lock />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>

            <el-form-item label="" prop="verifyCode">
                <el-input v-model="registerForm.verifyCode" placeholder="请输入验证码" clearable style="width: 70%;" />
                <div class="code-img">
                    <img :src="captchaImageSrc" alt="" @click="fetchCaptcha" style="cursor: pointer;" />
                    <!-- 使用 VerifyCode组件 -->
                    <VerifyCode ref="verifyCodeRef" @update:key="handleVerifyCodeKeyUpdate"/>
                </div>
            </el-form-item>
            <el-form-item label="" prop="role">
                <el-radio-group v-model="registerForm.role">
                    <el-radio value="student" size="large">学生</el-radio>
                    <el-radio value="teacher" size="large">教师</el-radio>
                </el-radio-group>
            </el-form-item>
            <!-- 按钮提交钮 -->
            <el-form-item class="btn-box">
                <el-button type="primary" native-type="reset" style="width: 40%;">重置</el-button>
                <el-button type="success" native-type="submit" style="width: 40%;"
                    @click.prevent="submitForm">注册</el-button>
            </el-form-item>
            <!-- 已有账号，去登录按钮 -->
            <el-form-item class="tologin">
                <router-link class="link-div" to="/login" style="font-size: 13px;">已有账号？去登录</router-link>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import JSEncrypt from 'jsencrypt';
import { UserFilled, Lock, Moon, Sunny } from '@element-plus/icons-vue';
import request from '@/utils/request';
import VerifyCode from '@/components/VerifyCode.vue'; // 导入 VerifyCode 组件
import { useUser } from '@/stores/userInfo.js';
import { useTheme } from '@/stores/themeStore';

const verifyCodeRef = ref(null);
const handleVerifyCodeKeyUpdate = (newKey) => {
    registerForm.verifyCodeKey = newKey;
};

// RSA加密函数
const encryptPassword = (password) => {
    const encrypt = new JSEncrypt();
    const publicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7rYgHiByM6LUO1Z7ZD80OKWl1O16/c+D1zRrrP5rYq/YSG+ZuP7Bjx3tcOgFmKL97ifyAbdNn9RmvyqBRqMt8YlT9vYXYQ8MirWbnBulhC9Q9j2ab/sUIDd1qdDIuAxx5i7X377M/IIrMTe1HTID646kwkKr/eUMZ1EEjX/Xnk2lJxj3sSzKuQ+LPMLrFQ1LP1jM6MNB4auDkrQ2vNEoI41gMy0PEE168nYrQWGkRdbolDX5GNDragi9my+Uv4J2hvf1GYDzDFs+FLK5ceUKFkkoGRHouqxkizxNAC2GlMGkJdKp2NXmvDdYvXl8VGutHPN2TnL2c875dRBEHb81zQIDAQAB';
    encrypt.setPublicKey(publicKey);
    return encrypt.encrypt(password);
};
const userStore = useUser();
const router = useRouter();
const labelPosition = ref('right');
const registerForm = reactive({
    username: '', // 用户名
    password: '', // 密码
    reType: '', // 确认密码
    schoolNumber: '', // 学号/工号
    verifyCode: '', // 验证码
    verifyCodeKey: '', // 验证码 Key
    role: 'student', // 角色
});
const captchaImageSrc = ref(''); // 验证码图片的 URL
const ruleFormRef = ref();
const themeStore = useTheme();
const isNightMode = computed(() => themeStore.isNightMode);

const toggleTheme = () => {
    themeStore.toggleTheme();
};

// 在组件挂载时初始化主题
onMounted(() => {
    themeStore.initTheme();
});

// 登录失败时刷新验证码
const refreshVerifyCode = () => {
    if (verifyCodeRef.value) {
        verifyCodeRef.value.handleClick();
    }
};
// 注册功能
const submitForm = async () => {
    ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            // 密码不一致
            if (registerForm.password !== registerForm.reType) {
                ElMessage.error('两次密码输入不一致');
                return;
            }
            try {
                const encryptedPassword = encryptPassword(registerForm.password); // 加密密码
                const response =await request.post('/nerv/signin', {
                    username: registerForm.username,
                    password: encryptedPassword, // 发送加密后的密码
                    school_number: registerForm.schoolNumber,
                    role: registerForm.role,
                    verifyCode: registerForm.verifyCode,
                    verifyCodeKey: registerForm.verifyCodeKey,
                });
                    
                console.log('Response:', response); // 打印响应数据
                if (response.data.code === 200) {
                    ElMessage.success(response.data.message || '注册成功');
                    // const {  username, role, school_numbe, token } = response.data.data;
                    // userStore.setUserInfo({  username, role,school_numbe, token });
                    // sessionStorage.setItem('userInfo', JSON.stringify(response.data.data));
                    router.push('/login'); // 跳转到登录页面
                } else {
                    ElMessage.error(response.data.message || '注册失败');
                    refreshVerifyCode(); // 注册失败时刷新验证码
                }
            } catch (error) {
                console.error('Register error:', error);
                if (error.response) {
                    console.error('Response status:', error.response.status);
                    console.error('Response data:', error.response.data);
                }
                ElMessage.error('注册失败，请检查网络或联系管理员');
                refreshVerifyCode();
            }
        } else {
            ElMessage.error('表单验证失败');
            console.log('error submit!', fields);
        }
    });
};


// 验证规则
const rules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    reType: [
        { required: true, message: '请输入确认密码', trigger: 'blur' },
    ],
    schoolNumber: [
        { required: true, message: '请输入学号/工号', trigger: 'blur' },
    ],
    verifyCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
    ],
    role: [
        { required: true, message: '请选择角色', trigger: 'change' },
    ],
});
</script>

<style scoped>
.theme-toggle {
    position: absolute;
    top: 20px;
    right: 20px;
    z-index: 10;
    cursor: pointer;
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.3s ease;
    backdrop-filter: blur(8px);
    border: 2px solid rgba(255, 255, 255, 0.3);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.night-mode .theme-toggle {
    background: rgba(0, 0, 0, 0.2);
    border-color: rgba(255, 255, 255, 0.1);
}

.theme-toggle:hover {
    transform: scale(1.1) rotate(5deg);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
}

.login-wrap {
    box-sizing: border-box;
    width: 100vw;
    height: 100vh;
    background: linear-gradient(
        45deg,
        #FF6B6B,
        #4ECDC4,
        #45B7D1,
        #A06CD5,
        #F7D794,
        #FF9A9E,
        #FAD0C4,
        #6991C7
    );
    background-size: 400% 400%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    animation: gradientBG 15s ease infinite;
    overflow: hidden;
    transition: all 0.8s ease;
}

.login-wrap.night-mode {
    background: linear-gradient(
        45deg,
        #0f2027,
        #203a43,
        #2c5364,
        #243b55,
        #141e30
    );
    background-size: 500% 500%;
}

/* 气泡容器 */
.bubbles {
    position: fixed;
    width: 100%;
    height: 100%;
    z-index: 2;
    overflow: hidden;
    top: 0;
    left: 0;
}

/* 气泡样式 */
.bubble {
    position: absolute;
    background: linear-gradient(
        135deg,
        rgba(255, 255, 255, 0.8),
        rgba(255, 255, 255, 0.4)
    );
    backdrop-filter: blur(5px);
    border-radius: 50%;
    box-shadow: 
        inset 0 0 20px rgba(255, 255, 255, 0.6),
        0 0 30px rgba(255, 255, 255, 0.4);
    animation: float 8s infinite;
    z-index: 2;
    border: 1px solid rgba(255, 255, 255, 0.6);
}

/* 随机气泡大小和位置 */
.bubble:nth-child(3n) { width: 40px; height: 40px; left: 10%; animation-delay: 0s; }
.bubble:nth-child(3n+1) { width: 60px; height: 60px; left: 20%; animation-delay: 2s; }
.bubble:nth-child(3n+2) { width: 50px; height: 50px; left: 30%; animation-delay: 4s; }
.bubble:nth-child(4n) { width: 55px; height: 55px; left: 40%; animation-delay: 1s; }
.bubble:nth-child(4n+1) { width: 45px; height: 45px; left: 50%; animation-delay: 3s; }
.bubble:nth-child(4n+2) { width: 65px; height: 65px; left: 60%; animation-delay: 5s; }
.bubble:nth-child(4n+3) { width: 35px; height: 35px; left: 70%; animation-delay: 0.5s; }
.bubble:nth-child(5n) { width: 70px; height: 70px; left: 80%; animation-delay: 2.5s; }
.bubble:nth-child(5n+1) { width: 55px; height: 55px; left: 90%; animation-delay: 4.5s; }

/* 浮动形状 */
.floating-shapes {
    position: fixed;
    width: 100%;
    height: 100%;
    z-index: 1;
    pointer-events: none;
}

.shape {
    position: absolute;
    background: linear-gradient(45deg, rgba(255,255,255,0.4), rgba(255,255,255,0.2));
    backdrop-filter: blur(8px);
    animation: floatShape 20s infinite;
    box-shadow: 0 0 40px rgba(255,255,255,0.3);
}

.shape.circle {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    left: 15%;
    top: 20%;
}

.shape.square {
    width: 80px;
    height: 80px;
    right: 15%;
    top: 30%;
    animation-delay: 5s;
}

.shape.triangle {
    width: 0;
    height: 0;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-bottom: 86.6px solid rgba(255,255,255,0.1);
    background: none;
    left: 50%;
    top: 70%;
    animation-delay: 10s;
}

@keyframes float {
    0% {
        transform: translateY(120vh) translateX(-20px) rotate(0);
        opacity: 0.8;
    }
    20% {
        transform: translateY(80vh) translateX(20px) rotate(90deg);
        opacity: 0.9;
    }
    40% {
        transform: translateY(60vh) translateX(-20px) rotate(180deg);
        opacity: 1;
    }
    60% {
        transform: translateY(40vh) translateX(20px) rotate(270deg);
        opacity: 0.9;
    }
    80% {
        transform: translateY(20vh) translateX(-20px) rotate(360deg);
        opacity: 0.8;
    }
    100% {
        transform: translateY(-50px) translateX(0) rotate(720deg);
        opacity: 0;
    }
}

@keyframes floatShape {
    0% {
        transform: translate(0, 0) rotate(0) scale(1);
        opacity: 0.3;
    }
    25% {
        transform: translate(50px, -30px) rotate(90deg) scale(1.2);
        opacity: 0.5;
    }
    50% {
        transform: translate(100px, 0) rotate(180deg) scale(0.8);
        opacity: 0.7;
    }
    75% {
        transform: translate(50px, 30px) rotate(270deg) scale(1.1);
        opacity: 0.5;
    }
    100% {
        transform: translate(0, 0) rotate(360deg) scale(1);
        opacity: 0.3;
    }
}

@keyframes gradientBG {
    0% {
        background-position: 0% 50%;
    }
    50% {
        background-position: 100% 150%;
    }
    100% {
        background-position: 0% 50%;
    }
}

/* 夜间模式调整 */
.night-mode .shape {
    opacity: 0.1;
}

.night-mode .bubble {
    background: linear-gradient(
        135deg,
        rgba(255, 255, 255, 0.3),
        rgba(255, 255, 255, 0.1)
    );
    box-shadow: 
        inset 0 0 20px rgba(255, 255, 255, 0.2),
        0 0 30px rgba(255, 255, 255, 0.1);
}

.login-container {
    width: 400px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    position: relative;
    transition: all 0.8s ease;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.5);
    z-index: 2;
    transform: translateY(0);
    animation: containerFloat 6s ease-in-out infinite;
}

.night-mode .login-container {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

@keyframes containerFloat {
    0%, 100% {
        transform: translateY(0);
    }
    50% {
        transform: translateY(-10px);
    }
}

@keyframes stars {
    0% {
        transform: translateY(0);
    }
    100% {
        transform: translateY(-350px);
    }
}

.center {
    text-align: center;
    font-size: 32px;
    margin-bottom: 30px;
    background: linear-gradient(45deg, #2196F3, #00BCD4);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    font-weight: 700;
    letter-spacing: 2px;
    transition: all 0.8s ease;
}

.night-mode .center {
    background: linear-gradient(45deg, #fff, #e0e0e0);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.night-mode :deep(.el-input__wrapper) {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.2);
}

.night-mode :deep(.el-input__inner) {
    color: #fff;
}

.night-mode :deep(.el-button) {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.2);
    color: #fff;
}

.night-mode :deep(.el-radio__label) {
    color: #fff;
}

.night-mode .link-div {
    color: #fff;
}

.el-input {
    height: 42px;
}

:deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

:deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #409EFF !important;
}

.input-icon {
    font-size: 18px;
    color: #909399;
}

.code-img {
    width: 28%;
    height: 42px;
    margin-left: 2%;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
}

.btn-box {
    margin-top: 20px;
}

:deep(.el-button) {
    height: 42px;
    border-radius: 8px;
    font-size: 16px;
    transition: all 0.3s ease;
    background: linear-gradient(45deg, #4ECDC4, #45B7D1);
    border: none;
    color: white;
    position: relative;
    overflow: hidden;
}

:deep(.el-button:hover) {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    background: linear-gradient(45deg, #45B7D1, #4ECDC4);
}

:deep(.el-button::before) {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(
        120deg,
        transparent,
        rgba(255, 255, 255, 0.3),
        transparent
    );
    transition: 0.5s;
}

:deep(.el-button:hover::before) {
    left: 100%;
}

.link-div {
    color: #409EFF;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.3s ease;
    margin-right: 10px;
}

.link-div:hover {
    color: #66b1ff;
}

:deep(.el-radio) {
    margin-right: 20px;
    .el-radio__label {
        color: #606266;
    }
}

:deep(.el-radio.is-checked) {
    .el-radio__label {
        color: #409EFF;
    }
}

:deep(.el-form-item__error) {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 4px;
}

/*让已有账号去登录靠右*/
:deep(.tologin>.el-form-item__content) {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
}

@keyframes float {
    0% {
        transform: translateY(100vh) translateX(0) rotate(0);
        opacity: 0;
    }
}

.bubble {
    background: linear-gradient(
        135deg,
        rgba(255, 255, 255, 0.4),
        rgba(255, 255, 255, 0.2)
    );
}
</style>